package io.github.echarts.common.util;

import java.awt.Color;

/**
 * Utility class for color operations.
 */
public class ColorUtils {

    /**
     * Converts a hex color string to a Color object.
     *
     * @param hexColor the hex color string (e.g., "#FF0000" for red)
     * @return the Color object
     */
    public static Color hexToColor(String hexColor) {
        if (hexColor == null || hexColor.isEmpty()) {
            return Color.BLACK;
        }
        
        String colorStr = hexColor;
        if (hexColor.startsWith("#")) {
            colorStr = hexColor.substring(1);
        }
        
        try {
            return new Color(
                Integer.parseInt(colorStr.substring(0, 2), 16),
                Integer.parseInt(colorStr.substring(2, 4), 16),
                Integer.parseInt(colorStr.substring(4, 6), 16)
            );
        } catch (Exception e) {
            return Color.BLACK;
        }
    }
    
    /**
     * Converts a Color object to a hex color string.
     *
     * @param color the Color object
     * @return the hex color string (e.g., "#FF0000" for red)
     */
    public static String colorToHex(Color color) {
        if (color == null) {
            color = Color.BLACK;
        }
        
        return String.format("#%02X%02X%02X", 
            color.getRed(), color.getGreen(), color.getBlue());
    }
    
    /**
     * Creates a color with the specified opacity.
     *
     * @param color the base color
     * @param opacity the opacity (0.0 to 1.0)
     * @return the new Color with the specified opacity
     */
    public static Color withOpacity(Color color, float opacity) {
        if (color == null) {
            color = Color.BLACK;
        }
        
        float alpha = Math.max(0.0f, Math.min(1.0f, opacity));
        return new Color(
            color.getRed() / 255f,
            color.getGreen() / 255f,
            color.getBlue() / 255f,
            alpha
        );
    }
} 